﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.Collections.Generic;
using System.Linq;
using FinPlusInterfaces;

namespace FinPlusBaseCore
{
    public class GPods : Dictionary<string, string>, IGPods
    {
        private readonly IPods _group;

        //construct
        public GPods(IPods pods)
        {
            _group = pods;
            _group.PodUpdate += GPod_Update;

            lock (_group)
            {
                foreach (var pod in _group.Values.Where(f => f[PodField.Type.ToString()].Equals(Common.PodMap.ToString())))
                    this[(string)pod[BeanField.Name.ToString()]] = (string)pod[Common.Group.ToString()];
            }
        }

        //event
        private void GPod_Update(object s, BeanEventArgs a)
        {
            try
            {
                var pod = (IPod)s;

                //note should only send group map collections
                if (!pod[PodField.Type.ToString()].ToString().Equals(Common.PodMap.ToString())) 
                    return;
  
                lock (_group)
                {
                    if (a.ChangeType == ChangeType.Removed)
                        this.Remove(pod[BeanField.Name.ToString()].ToString());
                    else if (a.ChangeType == ChangeType.New || a.ChangeType == ChangeType.Altered)
                        this[pod[BeanField.Name.ToString()].ToString()] = pod[Common.Group.ToString()].ToString();
                }
            }
            catch(Exception e)
            {
                throw new PodException(string.Format("Failed to update {0}", s.ToString()), e);
            }
        }
    }
}
